from django.shortcuts import render
from django.http.response import JsonResponse,HttpResponse
from rest_framework.views import APIView
from django.views import View
from rest_framework.response import Response
from django.db import transaction
from user.models import User
from goods.models import Table
from .models import OrderGoods,Orders
from .serializers import OrderGoodsSer
from decimal import Decimal
import time
import redis


class AddOrder(APIView):
    def post(self, request):
        "创建订单"
        # 1. 获取前端的用户和商品
        name = request.data.get('user')
        goods = request.data.get("products")
        print("goods>>>", goods)
        # 4. 创建订单编号
        order_id = str(time.time()).replace('.','')
        # 5. 创建当前时间
        created_time = time.strftime("%Y-%m-%d %H:%M:%S")
        # 3. 导入订单模型类写入订单模型类
        user = User.objects.get(username=name)

        # 在redis中把结算的商品减去
        redis_cli = redis.Redis()
        # 开启事务， 以原子特性开启
        with transaction.atomic():
            # 创建回滚的点
            points = transaction.savepoint()
            try:
                # 创建订单表
                order = Orders.objects.create(
                    order_id=order_id,
                    user_id=user.id,
                    created_time=created_time
                )
                # 创建订单商品表
                # 1.被勾选的商品才结算
                # 2. 判断库存，
                #   1. 库存不能小于购买量，小于的库存不足；
                #   2. 库存可以，把购买的商品数量减去， 更新商品的库存数量
                #3. 计算总价格： 每个商品的价格*每个商品的数量的和
                #4. 创建订单商品
                #5. 在redis中把结算的商品减去
                total_price = 0
                for item in goods:
                    while True:
                        # item 是商品的对象
                        print("item>>>", item['stock'])
                        old_stock =item['stock']
                        print("库存》》》", old_stock)
                        good_num = item['count']
                        print("购买量》》", good_num)
                        # 库存不能小于购买量，小于的库存不足；
                        if old_stock < good_num:
                            # 订单不足要先回滚
                            transaction.savepoint_rollback(points)
                            return Response({"msg":"库存不足","code":"500"})
                        else:
                            # 库存可以，把购买的商品数量减去， 更新商品的库存数量
                            new_stock = int(old_stock) - int(good_num)
                            # 更新的是这一个商品的库存
                            # 每次更新库存时会先查询旧的库存有咩有变化， 如果变化说名库存已经被修改过， 使用修改后的库存
                            # 若库存数量还是老的数量，说名库存没有被修改，就直接购买
                            # num 等于0 说名库存没有被修改， 若不等于0， 说明库存被更改，
                            num = Table.objects.filter(id=item['id'], stock=old_stock).update(stock=new_stock)
                            print("库存更新数量》》》",num)
                            # 不能0你说明库存被修改了，
                            if num != 0:
                                break
                            # 计算总价 计算总价格： 每个商品的价格*每个商品的数量的和
                            total_price += int(item['count']) * Decimal(item['selling_price'])
                    ordergoods = OrderGoods()
                    ordergoods.order=order
                    ordergoods.goods_id=item['id']
                    ordergoods.count = item['count']
                    ordergoods.price=item['selling_price']
                    ordergoods.save()
                    # 根据用户id 操作redis
                    redis_cli.hdel("cart_%s" % user.id, item['id'], item['count'])
                    # 继续循环
                    continue
            except Exception as e:
                # 出错回滚到回滚点
                print("e>>>",e)
                transaction.savepoint_rollback(points)
                return Response({"msg":"下单失败","code":"404"})
        # 提交事务
        transaction.savepoint_commit(points)
        return Response({"msg": "下单成功！", "code": "200"})



#
class GetOrderView1(APIView):
    def post(self, request):
#         "查询订单"

        # 1. 获取前端传来的用户
        name = request.data.get('user')
        try:
            user = User.objects.get(username=name)
        except Exception as e:
            return Response({"msg":"用户未登录","code":"403"})
        # 2. 查询当前用户的订单
        orders = user.orders_set.all()
        data=[]
        for order in orders:
            # 获取每个订单下的所有订单商品
            order_goods = order.ordergoods_set.all()
            # 序列化： 订单商品的序列化器进行序列化
            ser = OrderGoodsSer(order_goods, many=True)
            print("ser>>>", ser.data)
            data.append(ser.data)
            # print(ser.data)
            # 3. 根据订单查询订单商品
        return Response({"data":data,"code":"200"})


class GetOrderView(View):
    def get(self, request):
        # 获取前端传来的数据： post request.POST.get()
        name = request.GET.get('user')
        print("name>>", name)
        try:
            user = User.objects.get(username=name)
        except Exception as e:
               return Response({"msg":"用户未登录","code":"403"})
        # 2. 查询当前用户的订单
        orders = user.orders_set.all()
        resp_data = []
        data = {}
        # 取出每个订单
        for order in orders:
            # 根据订单号查询订单下的商品
            data['id']=order.order_id
            data['created_time']=order.created_time
            data['skus'] = []
            resp_data.append(data)
            # print("resp_data>>>",resp_data)
            # 取出订单商品表
            order_goods = order.ordergoods_set.all()
            # 取出每一个订单商品
            total_num = 0
            total_price = 0
            for order_good in order_goods:
                # 取出order_good下的商品
                # goods = order_good.goods
                # 商品总数量
                total_num += order_good.count
                total_price += order_good.count*order_good.goods.selling_price
                # 商品的总价格
                data['skus'].append({
                    "id":order_good.goods.id,
                    "sku_name":order_good.goods.sku_name,
                    "count":order_good.count,
                    "selling_price":order_good.goods.selling_price,
                    "img":order_good.goods.img,
                })
            data['total_price'] = total_price
            data['total_num'] = total_num
            # print("---------",resp_data)
        return JsonResponse({"data": resp_data})